<template>
  <div class="trace-detail-page">
    <!-- 商品信息大白块 -->
    <div class="product-info-block" style="position: relative;">
      <!-- 商品信息大白块右上角操作按钮 -->
      <div style="position: absolute; right: 32px; top: 24px; z-index: 10; display: flex; gap: 12px;">
        <el-button type="primary" @click="onEditDetail">修改</el-button>
        <el-button type="primary" @click="handleExportDetail">导出溯源码</el-button>
      </div>
      <div class="trace-detail-body">
        <!-- 左侧图片 -->
        <div class="trace-detail-img">
          <img :src="detail.coverImage" alt="商品图片" @dblclick="handleImgDblClick(detail.coverImage)" />
        </div>
        <!-- 右侧内容 -->
        <div class="trace-detail-content">
          <div class="trace-detail-title">
            {{ detail.goodsName }}
          </div>
          <div class="trace-detail-row">
            <span>生产批次：{{ detail.productionBatch }}</span>
            <span>保质期：{{ detail.shelfLifeDays }} 天</span>
          </div>
          <div class="trace-detail-row">
            <span>生产许可证号：{{ detail.productionLicenseNumber }}</span>
            <span>生产企业：{{ detail.manufacturingEnterprise }}</span>
          </div>
          <div class="trace-detail-section">
            <b>产品检验报告</b>
            <div class="trace-detail-report">
              <div class="report-img-list">
                <div v-for="(img, idx) in reportImageList" :key="img" class="report-img-item">
                  <img :src="img" class="report-img" @dblclick="handleImgDblClick(img)" />
                  <el-icon class="report-img-delete" @click="removeReportImg(img)">
                    <Close />
                  </el-icon>
                </div>
                <el-upload v-if="reportImageList.length < 9" class="report-uploader" :action="urlscr"
                  :show-file-list="false" :on-success="handleReportSuccess" :before-upload="beforeReportUpload"
                  :multiple="true" :limit="9 - reportImageList.length" :auto-upload="true"
                  :data="{ traceId: detail.id }" :disabled="reportImageList.length >= 9" accept="image/*">
                  <div class="report-upload-btn">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="trace-tabs">
      <div v-for="tab in tabList" :key="tab.key" :class="['trace-tab-item', { active: activeTab === tab.key }]"
        @click="activeTab = tab.key">
        {{ tab.label }} ({{ tab.count }}/{{ tab.total }})
        <el-icon style="margin-left: 4px; color: #ffd700;">
          <Lightning />
        </el-icon>
      </div>
    </div>
    <div style="width: 100%;">
      <div v-show="activeTab === 'breeding'">
        <!-- 养殖信息内容 -->
        <div>
          <!-- 养殖信息大白块 -->
          <div class="breeding-info-block2">
            <div class="breeding-info-card-header">
              <span class="breeding-info-card-title">养殖信息</span>
              <el-button size="small" class="breeding-info-card-set-btn" @click="openBreedingDialog">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="breedingDetail && breedingDetail.id" class="breeding-info-card-table">
              <div class="breeding-info-card-row">
                <div class="breeding-info-card-label">品种：</div>
                <div class="breeding-info-card-value">{{ breedingDetail.breed }}</div>
                <div class="breeding-info-card-label">来源：</div>
                <div class="breeding-info-card-value">{{ breedingDetail.source }}</div>
              </div>
              <div class="breeding-info-card-row">
                <div class="breeding-info-card-label">饲养天数：</div>
                <div class="breeding-info-card-value">{{ breedingDetail.breedingDays }} 天</div>
                <div class="breeding-info-card-label">饲料品牌：</div>
                <div class="breeding-info-card-value">{{ breedingDetail.feedBrand }}</div>
              </div>
              <div class="breeding-info-card-row">
                <div class="breeding-info-card-label">饲养负责人：</div>
                <div class="breeding-info-card-value">{{ breedingDetail.breedingPrincipal }}</div>
                <div class="breeding-info-card-label">出栏日期：</div>
                <div class="breeding-info-card-value">{{ moment(breedingDetail.outDate).format('YYYY年MM月DD日') }}</div>
              </div>
            </div>
            <div v-else class="breeding-info-card-empty">暂无养殖信息</div>
          </div>
          <!-- 保健信息大白块 -->
          <div class="health-info-block">
            <div class="block-header">
              <span class="block-title">保健信息</span>
              <el-button size="small" class="block-set-btn" @click="addRow">新建行</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <el-table :data="healthTable.length > 0 ? healthTable : [{}]" style="width: 100%;" border
              :header-cell-style="{ background: '#fafafa', fontWeight: 'bold' }">
              <el-table-column prop="breedingDays" label="饲养天数" width="120">
                <template #default="{ row, $index }">
                  <template v-if="isEditing($index)">
                    <el-input v-model="editRow.breedingDays" size="small" type="number" />
                  </template>
                  <template v-else>
                    <span v-if="row.breedingDays !== undefined">{{ row.breedingDays }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column prop="immunityType" label="保健方式" width="150">
                <template #default="{ row, $index }">
                  <template v-if="isEditing($index)">
                    <el-input v-model="editRow.immunityType" size="small" maxlength="50" />
                  </template>
                  <template v-else>
                    <span v-if="row.immunityType !== undefined">{{ row.immunityType }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column prop="immunityMethod" label="保健方法" width="150">
                <template #default="{ row, $index }">
                  <template v-if="isEditing($index)">
                    <el-input v-model="editRow.immunityMethod" size="small" maxlength="100" />
                  </template>
                  <template v-else>
                    <span v-if="row.immunityMethod !== undefined">{{ row.immunityMethod }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{ row, $index }">
                  <template v-if="isEditing($index)">
                    <el-button type="primary" size="small" @click="saveRow(row, $index)">保存</el-button>
                    <el-button size="small" @click="cancelEdit">取消</el-button>
                  </template>
                  <template v-else>
                    <el-button v-if="row.id" type="text" size="small" @click="editThisRow(row, $index)">修改</el-button>
                    <el-button v-if="row.id" type="text" size="small" @click="deleteRow(row)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 动物证大白块 -->
          <div class="animal-cert-block">
            <div class="block-header">
              <span class="block-title">动检证</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="animal-cert-img-list">
              <div v-for="img in animalCertImageList" :key="img.id" class="animal-cert-img-item">
                <img :src="baseUrl + img.url" class="animal-cert-img"
                  @dblclick="handleImgDblClick(baseUrl + img.url)" />
                <el-icon class="animal-cert-img-delete" @click="removeAnimalCertImg(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload v-if="animalCertImageList.length < 9" class="animal-cert-uploader"
                :action="animalCertUploadUrl" :show-file-list="false" :on-success="handleAnimalCertSuccess"
                :before-upload="beforeAnimalCertUpload" :auto-upload="true" :disabled="animalCertImageList.length >= 9"
                accept="image/*">
                <div class="animal-cert-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>
          <!-- 企业信息大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">企业信息</span>
              <el-button size="small" class="block-set-btn" @click="openCompanyInfoDialog(1)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="companyInfoDetail && companyInfoDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>养殖场：{{ companyInfoDetail.breed }}</div>
                <div>存栏数量：{{ companyInfoDetail.number }} 只</div>
              </div>
              <div class="company-info-content-right">
                <div>负责人：{{ companyInfoDetail.personInCharge }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 企业照片大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">企业照片</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoList" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeCompanyPhoto(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload v-if="companyPhotoList.length < 9" class="company-photo-uploader"
                :action="companyPhotoUploadUrl" :show-file-list="false" :on-success="handleCompanyPhotoSuccess"
                :before-upload="beforeCompanyPhotoUpload" :auto-upload="true" :disabled="companyPhotoList.length >= 9"
                accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeTab === 'slaughter'">
        <!-- 屠宰信息内容 -->
        <div>
          <!-- 屠宰信息大板块 -->
          <div class="slaughter-block">
            <div class="block-header">
              <span class="block-title">屠宰信息</span>
              <el-button size="small" class="breeding-info-card-set-btn" @click="openSlaughterDialog">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="slaughter-info-row">
              <div>批次：{{ slaughterDetail.batch }}</div>
              <div>到厂均重：{{ slaughterDetail.weight }} 公斤</div>
            </div>
            <div class="slaughter-info-row">
              <div v-if="slaughterDetail.id != null">到厂时间：{{ moment(slaughterDetail.arrivalTime).format('YYYY年MM月DD') }}
              </div>
              <div v-if="slaughterDetail.id != null">屠宰时间：{{ moment(slaughterDetail.slaughterTime).format('YYYY年MM月DD')
                }}
              </div>
              <div v-if="slaughterDetail.id == null">到厂时间：</div>
              <div v-if="slaughterDetail.id == null">屠宰时间：</div>
            </div>
          </div>
          <!-- 相关资质模块 -->
          <div class="slaughter-block">
            <div class="qualification-photo-block">
              <div class="block-header">
                <span class="block-title">相关资质照片</span>
              </div>
              <el-divider style="margin: 12px 0 18px 0;" />
              <div class="company-photo-img-list">
                <div v-for="img in qualificationPhotoList" :key="img.id" class="company-photo-img-item">
                  <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                    @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                  <el-icon class="company-photo-img-delete" @click="removeQualificationPhoto(img)">
                    <Close />
                  </el-icon>
                </div>
                <el-upload v-if="qualificationPhotoList.length < 9" class="company-photo-uploader"
                  :action="qualificationPhotoUploadUrl" :show-file-list="false"
                  :on-success="(handleQualificationPhotoSuccess)" :before-upload="beforeQualificationPhotoUpload"
                  :auto-upload="true" :disabled="qualificationPhotoList.length >= 9"
                  :data="{ slaughterId: slaughterDetail.id }" accept="image/*">
                  <div class="company-photo-upload-btn">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
          <!-- 企业信息大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">企业信息</span>
              <el-button size="small" class="block-set-btn" @click="openCompanyInfoDialog(2)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="companyInfoDetail && companyInfoDetail.id" class="company-info-content-row">
              <div class="company-info-content-row">
                <div class="company-info-content-left">
                  <div>公司名称：{{ companyInfoDetail.companyName }}</div>
                  <div style="margin-top: 8px;">
                    公司简介：
                    <div class="company-profile-text">{{ companyInfoDetail.companyProfile }}</div>
                  </div>
                </div>
                <div class="company-info-content-right">
                  <div>公司地址：{{ companyInfoDetail.city }}</div>
                  <div style="margin-top: 8px;">
                    成立时间：{{ moment(companyInfoDetail.establishmentTime).format('YYYY年MM月DD日') }}
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 企业照片大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">企业照片</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoList" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeCompanyPhoto(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload v-if="companyPhotoList.length < 9" class="company-photo-uploader"
                :action="companyPhotoUploadUrl" :show-file-list="false" :on-success="handleCompanyPhotoSuccess"
                :before-upload="beforeCompanyPhotoUpload" :auto-upload="true" :disabled="companyPhotoList.length >= 9"
                accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeTab === 'process'">
        <!-- 深加工信息内容 -->
        <div>
          <!-- 深加工信息大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">深加工信息</span>
              <el-button size="small" class="block-set-btn" @click="openProcessingDialog">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="processingDetail && processingDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>班组：:{{ processingDetail.teamsAndGroups }}</div>
              </div>
              <div class="company-info-content-right">
                <div>负责人：:{{ processingDetail.personInCharge }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 食品安全信息大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">食品安全信息</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoListDesc" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeQualificationPhotos(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload class="company-photo-uploader" v-if="companyPhotoListDesc.length < 9"
                :action="DeepacuPhotoUploadUrl" :show-file-list="false" :on-success="handleQualificationPhotoSuccessDes"
                :before-upload="beforeCompanyPhotoUploads" :auto-upload="true"
                :disabled="companyPhotoListDesc.length >= 9" accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>

          <!-- 供应商信息大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">原料</span>
              <el-button size="small" class="block-set-btn" @click="openProcessingDialogs(1)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="processingDetail && processingDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>生产批次:{{ processingDetail.rawMaterial }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 相关材料大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">相关材料</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoListDescsy" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeQualificationPhotossy(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload class="company-photo-uploader" v-if="companyPhotoListDescsy.length < 9"
                :action="DeepacuPhotoUploadUrly" :show-file-list="false"
                :on-success="handleQualificationPhotoSuccessDessy" :before-upload="beforeCompanyPhotoUploadssy"
                :auto-upload="true" :disabled="companyPhotoListDescsy.length >= 9" accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>

          <!-- 辅料大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">辅料</span>
              <el-button size="small" class="block-set-btn" @click="openProcessingDialogs(2)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="processingDetail && processingDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>生产批次:{{ processingDetail.auxiliaryMaterials }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 相关材料大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">相关材料</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoListDescsyf" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeQualificationPhotossyf(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload class="company-photo-uploader" v-if="companyPhotoListDescsyf.length < 9"
                :action="DeepacuPhotoUploadUrlf" :show-file-list="false"
                :on-success="handleQualificationPhotoSuccessDessyf" :before-upload="beforeCompanyPhotoUploadssyf"
                :auto-upload="true" :disabled="companyPhotoListDescsyf.length >= 9" accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>

          <!-- 添加剂大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">添加剂</span>
              <el-button size="small" class="block-set-btn" @click="openProcessingDialogs(3)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="processingDetail && processingDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>生产批次:{{ processingDetail.additive }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 相关材料大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">相关材料</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoListDescsyt" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeQualificationPhotossyt(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload class="company-photo-uploader" v-if="companyPhotoListDescsyt.length < 9"
                :action="DeepacuPhotoUploadUrlt" :show-file-list="false"
                :on-success="handleQualificationPhotoSuccessDessyt" :before-upload="beforeCompanyPhotoUploadssyt"
                :auto-upload="true" :disabled="companyPhotoListDescsyt.length >= 9" accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>


          <!-- 包材大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">包材</span>
              <el-button size="small" class="block-set-btn" @click="openProcessingDialogs(4)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="processingDetail && processingDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>生产批次:{{ processingDetail.baoCai }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 相关材料大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">相关材料</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoListDescsyb" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeQualificationPhotossyb(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload class="company-photo-uploader" v-if="companyPhotoListDescsyb.length < 9"
                :action="DeepacuPhotoUploadUrlb" :show-file-list="false"
                :on-success="handleQualificationPhotoSuccessDessyb" :before-upload="beforeCompanyPhotoUploadssyb"
                :auto-upload="true" :disabled="companyPhotoListDescsyb.length >= 9" accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>

          <!-- 企业信息大白块 -->
          <div class="company-info-block">
            <div class="block-header">
              <span class="block-title">企业信息</span>
              <el-button size="small" class="block-set-btn" @click="openCompanyInfoDialog(3)">设置</el-button>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div v-if="companyInfoDetail && companyInfoDetail.id" class="company-info-content-row">
              <div class="company-info-content-left">
                <div>公司名称:{{ companyInfoDetail.companyName }}</div>
              </div>
              <div class="company-info-content-right">
                <div>生产许可证号:{{ companyInfoDetail.productionLicenseNumber }}</div>
              </div>
            </div>
            <div v-else class="company-info-empty">暂无企业信息</div>
          </div>
          <!-- 企业照片大白块 -->
          <div class="company-photo-block">
            <div class="block-header">
              <span class="block-title">企业照片</span>
            </div>
            <el-divider style="margin: 12px 0 18px 0;" />
            <div class="company-photo-img-list">
              <div v-for="img in companyPhotoList" :key="img.id" class="company-photo-img-item">
                <img :src="baseUrl + img.phoneFile" class="company-photo-img"
                  @dblclick="handleImgDblClick(baseUrl + img.phoneFile)" />
                <el-icon class="company-photo-img-delete" @click="removeCompanyPhoto(img)">
                  <Close />
                </el-icon>
              </div>
              <el-upload v-if="companyPhotoList.length < 9" class="company-photo-uploader"
                :action="companyPhotoUploadUrl" :show-file-list="false" :on-success="handleCompanyPhotoSuccess"
                :before-upload="beforeCompanyPhotoUpload" :auto-upload="true" :disabled="companyPhotoList.length >= 9"
                accept="image/*">
                <div class="company-photo-upload-btn">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>


  <!-- 养殖信息设置弹窗 -->
  <el-dialog v-model="breedingDialogVisible" title="设置养殖信息" width="500px">
    <el-form :model="breedingForm" :rules="breedingRules" ref="breedingFormRef" label-width="120px">
      <el-form-item label="品种" prop="breed" required>
        <el-input v-model="breedingForm.breed" />
      </el-form-item>
      <el-form-item label="来源" prop="source" required>
        <el-input v-model="breedingForm.source" />
      </el-form-item>
      <el-form-item label="饲养天数" prop="breedingDays" required>
        <el-input v-model.number="breedingForm.breedingDays" />
      </el-form-item>
      <el-form-item label="饲料品牌" prop="feedBrand" required>
        <el-input v-model="breedingForm.feedBrand" />
      </el-form-item>
      <el-form-item label="饲养负责人" prop="breedingPrincipal" required>
        <el-input v-model="breedingForm.breedingPrincipal" />
      </el-form-item>
      <el-form-item label="出栏日期" prop="outDate" required>
        <el-date-picker v-model="breedingForm.outDate" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="breedingDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleBreedingSave">保存</el-button>
    </template>
  </el-dialog>
  <!-- 企业信息设置弹窗1 -->
  <el-dialog v-model="companyInfoDialogVisible" title="设置企业信息" width="500px">
    <el-form :model="companyInfoForm" :rules="companyInfoRules" ref="companyInfoFormRef" label-width="120px">
      <el-form-item label="养殖场" prop="breed" required>
        <el-input v-model="companyInfoForm.breed" />
      </el-form-item>
      <el-form-item label="负责人" prop="personInCharge" required>
        <el-input v-model="companyInfoForm.personInCharge" />
      </el-form-item>
      <el-form-item label="存栏数量（只）" prop="number" required>
        <el-input v-model.number="companyInfoForm.number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="companyInfoDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleCompanyInfoSave">保存</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="slaughterDialogVisible" title="屠宰信息" width="500px">
    <el-form :model="slaughterForm" :rules="slaughterRules" ref="slaughterFormRef" label-width="120px">
      <el-form-item label="批次" prop="batch">
        <el-input v-model="slaughterForm.batch" />
      </el-form-item>
      <el-form-item label="到厂均重(公斤)" prop="weight">
        <el-input v-model="slaughterForm.weight" type="number" />
      </el-form-item>
      <el-form-item label="到厂时间" prop="arrivalTime">
        <el-date-picker v-model="slaughterForm.arrivalTime" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="屠宰时间" prop="slaughterTime">
        <el-date-picker v-model="slaughterForm.slaughterTime" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="slaughterDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveSlaughter">保存</el-button>
    </template>
  </el-dialog>
  <!-- 企业信息弹窗2 -->
  <el-dialog v-model="companyInfoDialogVisible1" title="企业信息" width="600px" @close="onCompanyInfoDialogClose">
    <el-form :model="companyInfoForm" :rules="companyInfoRules" ref="companyInfoFormRef" label-width="100px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="companyInfoForm.companyName" maxlength="30" show-word-limit placeholder="请输入公司名称"
          @input="companyInfoForm.companyName = filterSpecialChar(companyInfoForm.companyName)" />
      </el-form-item>
      <el-form-item label="公司地址" required>
        <el-cascader v-model="companyInfoForm.cityArr" @change="handleCityChange" :options="provinceOptions"
          placeholder="请选择省市县" style="width: 70%; margin-right: 8px" />
      </el-form-item>
      <el-form-item label="成立时间" prop="establishmentTime">
        <el-date-picker v-model="companyInfoForm.establishmentTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择成立日期" style="width: 100%" />
      </el-form-item>
      <el-form-item label="公司简介" prop="companyProfile">
        <el-input v-model="companyInfoForm.companyProfile" type="textarea" maxlength="500" show-word-limit
          @input="companyInfoForm.companyProfile = filterSpecialChar(companyInfoForm.companyProfile)"
          placeholder="请输入公司简介" rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="companyInfoDialogVisible1 = false">关闭</el-button>
      <el-button type="primary" @click="handleCompanyInfoSave">保存</el-button>
    </template>
  </el-dialog>
  <!-- 企业信息弹窗3 -->
  <el-dialog v-model="companyInfoDialogVisible2" title="企业信息" width="600px" @close="onCompanyInfoDialogClose">
    <el-form :model="companyInfoForm" :rules="companyInfoRules" ref="companyInfoFormRef" label-width="100px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="companyInfoForm.companyName" maxlength="30" show-word-limit placeholder="请输入公司名称"
          @input="companyInfoForm.companyName = filterSpecialChar(companyInfoForm.companyName)" />
      </el-form-item>
      <el-form-item label="生产许可证号">
        <el-input v-model="companyInfoForm.productionLicenseNumber" maxlength="30" show-word-limit
          placeholder="请输入生产许可证号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="companyInfoDialogVisible1 = false">关闭</el-button>
      <el-button type="primary" @click="handleCompanyInfoSave">保存</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="previewImgVisible" width="auto" top="5vh" :show-close="false" class="img-preview-dialog"
    @click.self="previewImgVisible = false">
    <img :src="previewImgUrl" style="max-width: 90vw; max-height: 80vh; display: block; margin: 0 auto;" />
  </el-dialog>
  <!-- 修改溯源商品弹窗 -->
  <el-dialog title="修改溯源商品" v-model="editDialogVisible" width="500px">
    <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
      <el-form-item label="商品名称" prop="productName" required>
        <el-select v-model="editForm.productName" placeholder="请选择商品名称" size="large" style="width: 240px">
          <el-option v-for="item in bindname" :label="item.goodsname" :value="item.id" :key="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次" prop="productionBatch" required>
        <el-input v-model="editForm.productionBatch" maxlength="30" />
      </el-form-item>
      <el-form-item label="保质期（天）" prop="shelfLifeDays" required>
        <el-input v-model.number="editForm.shelfLifeDays" />
      </el-form-item>
      <el-form-item label="生产许可证号" prop="productionLicenseNumber" required>
        <el-input v-model="editForm.productionLicenseNumber" maxlength="30" />
      </el-form-item>
      <el-form-item label="生产企业" prop="manufacturingEnterprise" required>
        <el-input v-model="editForm.manufacturingEnterprise" maxlength="30" />
      </el-form-item>
      <el-form-item label="封面图" prop="coverImage" required>
        <el-upload class="avatar-uploader" action="http://10.222.11.20:5174/api/Img/Upload" :show-file-list="false"
          :on-success="handleEditAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="editForm.coverImage" :src="editForm.coverImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onEditSubmitDetail">保存</el-button>
    </div>
  </el-dialog>
  <!-- 深加工信息弹窗 -->
  <el-dialog v-model="processingDialogVisible" title="深加工信息" width="500px">
    <el-form :model="processingForm" :rules="processingRules" ref="processingFormRef" label-width="100px">
      <el-form-item label="班组" prop="teamsAndGroups" required>
        <el-input v-model="processingForm.teamsAndGroups" placeholder="请输入班组" />
      </el-form-item>
      <el-form-item label="负责人" prop="personInCharge" required>
        <el-input v-model="processingForm.personInCharge" placeholder="请输入负责人" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="processingDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleProcessingSave">保存</el-button>
    </template>
  </el-dialog>
  <!-- 深加工信息弹窗 -->
  <el-dialog v-model="processingDialogVisibles" title="深加工信息" width="500px">
    <el-form :model="processingForm" :rules="processingRules" ref="processingFormRef" label-width="100px">
      <el-form-item v-if="nums == 1" label="生产批次" required>
        <el-input v-model="processingForm.rawMaterial" placeholder="请输入生产批次" />
      </el-form-item>
      <el-form-item v-if="nums == 2" label="生产批次" required>
        <el-input v-model="processingForm.auxiliaryMaterials" placeholder="请输入生产批次" />
      </el-form-item>
      <el-form-item v-if="nums == 3" label="生产批次" required>
        <el-input v-model="processingForm.additive" placeholder="请输入生产批次" />
      </el-form-item>
      <el-form-item v-if="nums == 4" label="生产批次" required>
        <el-input v-model="processingForm.baoCai" placeholder="请输入生产批次" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="processingDialogVisibles = false">取消</el-button>
      <el-button type="primary" @click="handleProcessingSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Plus, Close, Lightning } from '@element-plus/icons-vue';
import { axiostraceabliityw } from '@/http/axiosWrtie';
import { ElMessage } from 'element-plus';
import moment from 'moment';


const bindname = ref()
const bind = () => {
  axiostraceabliityr.get('/api/Traceability/GetGoodsAll').then((res: any) => {
    bindname.value = res.data.data
    console.log(bindname.value);
  })
}
const route = useRoute();
const router = useRouter();
const detail = ref<any>({
  id: route.query.id,
  coverImage: '',
  goodsId: 0,
  goodsName: '',
  productionBatch: '',
  shelfLifeDays: '',
  productionLicenseNumber: '',
  manufacturingEnterprise: '',
  reportImageList: ''
});
import provinceOptions from '@/assets/province-options.json'

const baseUrl = 'http://10.222.11.20:5174';

const urlscr = `http://10.222.11.20:5174/api/Img/UploadReportImage?traceId=` + route.query.id

const reportImageList = ref<string[]>([]);

const breedingDetail = ref<any>({});

const breedingDialogVisible = ref(false);
const breedingForm = ref({
  productTraceabilityId: 0,
  breed: '',
  source: '',
  breedingDays: '',
  feedBrand: '',
  breedingPrincipal: '',
  outDate: ''
});
const breedingFormRef = ref();
const breedingRules = {
  breed: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
  breedingDays: [{ required: true, message: '请输入饲养天数', trigger: 'blur' }],
  feedBrand: [{ required: true, message: '请输入饲料品牌', trigger: 'blur' }],
  breedingPrincipal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  outDate: [{ required: true, message: '请选择出栏日期', trigger: 'change' }]
};

const handleReportSuccess = (res: any) => {
  if (res.code === 200 && res.data) {
    reportImageList.value = res.data.map((img: string) => img.startsWith('http') ? img : baseUrl + img);
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(res.msg || '上传失败');
  }
};
const beforeReportUpload = (file: File) => {
  if (reportImageList.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片');
    return false;
  }
  return true;
};
const removeReportImg = async (img: string) => {
  const res = await axiostraceabliityw.post('/api/Img/DeleteReportImage', null, {
    params: {
      traceId: detail.value.id,
      imgPath: img
    }
  });
  if (res.data.code === 200) {
    reportImageList.value = res.data.data;
    ElMessage.success('删除成功');
    finds()
  } else {
    ElMessage.error(res.data.msg || '删除失败');
  }
};


const finds = (async () => {
  const id = route.query.id;
  await axiostraceabliityw.get(`/api/Traceability/GetDetail`, { params: { id } }).then((res) => {
    detail.value = res.data.data
  })
  let imgs = detail.value.reportImageList;
  if (!Array.isArray(imgs)) {
    imgs = typeof imgs === 'string' && imgs
      ? imgs.split(',').filter(Boolean)
      : [];
  }
  reportImageList.value = imgs.map((img: string) => img.startsWith('http') ? img : baseUrl + img);
})

const getBreedingDetail = async (productTraceabilityId: number) => {
  const res = await axiostraceabliityr.get('/api/Traceability/GetProductTraceabilityBreedingDetail', {
    params: { ProductTraceabilityId: productTraceabilityId }
  });
  if (res.data && res.data.code === 200) {
    breedingDetail.value = res.data.data;
  } else {
    breedingDetail.value = {};
  }
};

const openBreedingDialog = () => {
  breedingForm.value = {
    productTraceabilityId: detail.value.id,
    breed: breedingDetail.value.breed || '',
    source: breedingDetail.value.source || '',
    breedingDays: breedingDetail.value.breedingDays || '',
    feedBrand: breedingDetail.value.feedBrand || '',
    breedingPrincipal: breedingDetail.value.breedingPrincipal || '',
    outDate: breedingDetail.value.outDate || ''
  };
  breedingDialogVisible.value = true;
};

const handleBreedingSave = () => {
  breedingFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    // 判断是新增还是修改
    const isEdit = breedingDetail.value && breedingDetail.value.id;
    const url = isEdit
      ? '/api/Traceability/UpdateProductTraceabilityBreeding'
      : '/api/Traceability/AddProductTraceabilityBreeding';
    const payload = { ...breedingForm.value };
    if (isEdit) (payload as any).id = breedingDetail.value.id;
    const res = await axiostraceabliityw.post(url, payload);
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || (isEdit ? '修改成功' : '新增成功'));
      breedingDialogVisible.value = false;
      await getBreedingDetail(detail.value.id);
    } else {
      ElMessage.error(res.data.msg || '保存失败');
    }
  });
};



import { reactive } from 'vue'
import { ElMessageBox } from 'element-plus'

const productTraceabilityId = route.query.id // 需根据实际数据获取

const healthTable = ref<any[]>([])
const editIndex = ref(-1)
const editRow = reactive<any>({
  id: null,
  breedingDays: '',
  immunityType: '',
  immunityMethod: ''
})

// 获取列表
const fetchHealthList = async () => {
  const res = await axiostraceabliityr.get('/api/Traceability/GetProductTraceabilityImmunityList', {
    params: { productTraceabilityId }
  })
  healthTable.value = Array.isArray(res.data.data) ? res.data.data : []
}

// 新增行
const addRow = () => {
  if (editIndex.value !== -1) return
  if (!Array.isArray(healthTable.value)) healthTable.value = []
  editIndex.value = healthTable.value.length
  Object.assign(editRow, { id: null, breedingDays: '', immunityType: '', immunityMethod: '' })
  healthTable.value.push({ ...editRow })
}

// 编辑行
const editThisRow = (row: any, idx: number) => {
  if (editIndex.value !== -1) return
  editIndex.value = idx
  Object.assign(editRow, row)
}

// 判断是否编辑状态
const isEditing = (idx: number) => editIndex.value === idx

// 取消编辑
const cancelEdit = () => {
  if (editRow.id == null) healthTable.value.pop()
  editIndex.value = -1
}

// 保存
const saveRow = async (row: any, idx: number) => {
  if (!editRow.breedingDays || !editRow.immunityType || !editRow.immunityMethod) {
    ElMessage.warning('请填写完整信息')
    return
  }
  let res
  if (editRow.id) {
    res = await axiostraceabliityw.put('/api/Traceability/UpdateProductTraceabilityImmunity', {
      ...editRow,
      productTraceabilityId
    })
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg)
      editIndex.value = -1
      await fetchHealthList()
    }
    else {
      ElMessage.error(res.data.msg)
    }
  } else {
    res = await axiostraceabliityw.post('/api/Traceability/AddProductTraceabilityImmunity', {
      ...editRow,
      productTraceabilityId
    })
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg)
      editIndex.value = -1
      await fetchHealthList()
    }
    else {
      ElMessage.error(res.data.msg)
    }
  }
  if (res && (typeof res.data === 'number' ? res.data > 0 : false)) {
    ElMessage.success('保存成功')
    editIndex.value = -1
    await fetchHealthList()
  }
}

// 删除
const deleteRow = (row: any) => {
  ElMessageBox.confirm('确定删除该行吗？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await axiostraceabliityw.delete('/api/Traceability/DeleteProductTraceabilityImmunity', {
        params: { id: row.id }
      })
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg)
        await fetchHealthList()
      }
      else {
        ElMessage.error(res.data.msg)
      }
    })
}

onMounted(fetchHealthList)

const animalCertImageList = ref<any[]>([])
const animalCertUploadUrl = computed(() => `http://10.222.11.20:5174/api/Img/UploadAnimalCertImage?traceId=${detail.value.id}`)

const handleAnimalCertSuccess = (res: any) => {
  if (res.code === 200 && res.data) {
    animalCertImageList.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeAnimalCertUpload = (file: File) => {
  if (animalCertImageList.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
const removeAnimalCertImg = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/Img/DeleteAnimalCertImage', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    animalCertImageList.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
const fetchAnimalCertImages = async () => {
  const res = await axiostraceabliityw.get('/api/Img/GetAnimalCertImages', { params: { traceId: detail.value.id } })
  if (res.data.code === 200) {
    animalCertImageList.value = res.data.data
  }
}


const companyInfoDialogVisible = ref(false)
const companyInfoDialogVisible1 = ref(false)
const companyInfoDialogVisible2 = ref(false)
const companyInfoForm = ref({
  breed: '',
  personInCharge: '',
  number: '',
  companyName: '',
  cityArr: [],
  city: '',
  establishmentTime: '',
  companyProfile: '',
  productionLicenseNumber: ''
})
const handleCityChange = (val: any) => {
  companyInfoForm.value.cityArr = val
}
const companyInfoFormRef = ref()
const companyInfoRules = {
  breed: [{ required: true, message: '请输入养殖场', trigger: 'blur' }],
  personInCharge: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  number: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' },
    { type: 'number', message: '只能输入数字', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请填写公司名称', trigger: 'blur' },
    { max: 30, message: '最多30位字符', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (/[，。？、；：“”‘’！￥……（）——【】《》,.?;:"'!@#$%^&*()_+\-=\[\]{}|<>/\\]/.test(value)) {
          callback(new Error('不允许输入特殊字符'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  establishmentTime: [{ required: true, message: '请选择成立时间', trigger: 'change' }]
}

// 过滤特殊字符
const filterSpecialChar = (value: string) => value.replace(/[，。？、；：“”‘’！￥……（）——【】《》,.?;:"'!@#$%^&*()_+\-=\[\]{}|<>/\\]/g, '')

const companyInfoDetail = ref<any>({})

const openCompanyInfoDialog = (boos: any) => {
  companyInfoForm.value.breed = companyInfoDetail.value.breed || '',
    companyInfoForm.value.personInCharge = companyInfoDetail.value.personInCharge || '',
    companyInfoForm.value.number = companyInfoDetail.value.number || ''
  companyInfoForm.value.companyName = companyInfoDetail.value.companyName || ''
  companyInfoForm.value.cityArr = companyInfoDetail.value.city ? companyInfoDetail.value.city.split(',') : []
  companyInfoForm.value.city = companyInfoForm.value.cityArr.toString()
  companyInfoForm.value.establishmentTime = companyInfoDetail.value.establishmentTime ? companyInfoDetail.value.establishmentTime.substr(0, 10) : ''
  companyInfoForm.value.companyProfile = companyInfoDetail.value.companyProfile || ''
  companyInfoForm.value.productionLicenseNumber = companyInfoDetail.value.productionLicenseNumber || ''
  if (boos == 1) {
    companyInfoDialogVisible.value = true
    return
  }
  else if (boos == 2) {
    companyInfoDialogVisible1.value = true
  }
  else if (boos == 3) {
    companyInfoDialogVisible2.value = true
  }
}
// 关闭弹窗时重置
const onCompanyInfoDialogClose = () => {
  companyInfoForm.value.companyName = ''
  companyInfoForm.value.cityArr = []
  companyInfoForm.value.city = ''
  companyInfoForm.value.establishmentTime = ''
  companyInfoForm.value.companyProfile = ''
  companyInfoForm.value.productionLicenseNumber = ''
}
const handleCompanyInfoSave = () => {
  companyInfoForm.value.city = companyInfoForm.value.cityArr.toString()
  console.log(companyInfoForm.value.city);
  companyInfoFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    const isEdit = companyInfoDetail.value && companyInfoDetail.value.id
    const url = isEdit
      ? '/api/Traceability/UpdateProductTraceabilityCompanyInfo'
      : '/api/Traceability/AddProductTraceabilityCompanyInfo'
    const payload = {
      ...companyInfoForm.value,
      productTraceabilityId: detail.value.id
    }
    if (isEdit) (payload as any).id = companyInfoDetail.value.id
    const res = await axiostraceabliityw.post(url, payload)
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || (isEdit ? '修改成功' : '新增成功'))
      companyInfoDialogVisible.value = false
      companyInfoDialogVisible1.value = false
      companyInfoDialogVisible2.value = false
      await getCompanyInfoDetail(detail.value.id)
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  })
}

const getCompanyInfoDetail = async (productTraceabilityId: number) => {
  const res = await axiostraceabliityr.get('/api/Traceability/GetProductTraceabilityCompanyInfoDetail', {
    params: { productTraceabilityId }
  })
  if (res.data && res.data.code === 200) {
    companyInfoDetail.value = res.data.data
    fetchCompanyPhotos(res.data.data.id)
  } else {
    companyInfoDetail.value = {}
  }
}



const tabList = [
  { label: '养殖信息', key: 'breeding', count: 5, total: 5 },
  { label: '屠宰信息', key: 'slaughter', count: 5, total: 5 },
  { label: '深加工信息', key: 'process', count: 0, total: 5 }
]
const activeTab = ref('breeding')

const companyPhotoList = ref<any[]>([])
const companyPhotoUploadUrl = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${companyInfoDetail.value.id}`)
const handleCompanyPhotoSuccess = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoList.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUpload = (file: File) => {
  if (companyPhotoList.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
const removeCompanyPhoto = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoList.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
const fetchCompanyPhotos = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoList.value = res.data.data
  }
}

const slaughterDetail = ref<any>({})
const slaughterDialogVisible = ref(false)
const slaughterForm = ref<any>({
  id: undefined,
  productTraceabilityId: route.query.id,
  batch: '',
  weight: '',
  arrivalTime: null,
  slaughterTime: null
})
const slaughterFormRef = ref()
const slaughterRules = {
  batch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入到厂均重', trigger: 'blur' }],
  arrivalTime: [{ required: true, message: '请选择到厂时间', trigger: 'change' }],
  slaughterTime: [{ required: true, message: '请选择屠宰时间', trigger: 'change' }]
}

let slaughterId = localStorage.getItem('slaughterId')

const fetchSlaughterDetail = async () => {
  const res = await axiostraceabliityr.get('/api/Slaughter/GetDetail', { params: { productTraceabilityId: route.query.id } })
  if (res.data.data.code == 200) {
    slaughterDetail.value = res.data.data.data
    fetchQualificationPhotos(slaughterDetail.value.id)
    localStorage.setItem('slaughterId', slaughterDetail.value.id)
  }
}

const openSlaughterDialog = () => {
  slaughterForm.value = { ...slaughterDetail.value, productTraceabilityId: detail.value.id }
  slaughterDialogVisible.value = true
}

const saveSlaughter = () => {
  slaughterFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 转换为 ISO 字符串
      const payload = { ...slaughterForm.value }
      if (payload.arrivalTime) {
        payload.arrivalTime = new Date(payload.arrivalTime).toISOString()
      }
      if (payload.slaughterTime) {
        payload.slaughterTime = new Date(payload.slaughterTime).toISOString()
      }
      const res = await axiostraceabliityw.post('/api/Slaughter/AddOrUpdate', payload)
      if (res.data && res.data.code === 200) {
        ElMessage.success(res.data.msg || '保存成功')
        slaughterDialogVisible.value = false
        fetchSlaughterDetail()
      } else {
        ElMessage.error(res.data.msg || '保存失败')
      }
    }
  })
}




// 相关资质图片列表
const qualificationPhotoList = ref<any[]>([])
// 上传接口
const qualificationPhotoUploadUrl = computed(() =>
  `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${slaughterId}`
)

// 获取相关资质图片
const fetchQualificationPhotos = async (id: any) => {
  if (!slaughterDetail.value.id) return
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', {
    params: { traceId: id }
  })
  if (res.data.code === 200) {
    qualificationPhotoList.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccess = (res: any) => {
  if (res.code === 200 && res.data) {
    qualificationPhotoList.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

// 上传前校验
const beforeQualificationPhotoUpload = (file: File) => {
  if (qualificationPhotoList.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}

// 删除图片
const removeQualificationPhoto = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    qualificationPhotoList.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}


const previewImgVisible = ref(false)
const previewImgUrl = ref('')
const handleImgDblClick = (imgSrc: string) => {
  previewImgUrl.value = imgSrc
  previewImgVisible.value = true
}


const handleExportDetail = async () => {
  try {
    const res = await axiostraceabliityw.post(
      '/api/Traceability/ExportCodes',
      { id: detail.value.id },
      { responseType: 'blob' }
    )
    const blob = new Blob([res.data], { type: 'application/zip' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '溯源码二维码.zip'
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (e) {
    ElMessage.error('导出失败')
  }
}
const editDialogVisible = ref(false)
const editForm = ref({
  id: route.query.id,
  productName: '',
  productionBatch: '',
  shelfLifeDays: '',
  productionLicenseNumber: '',
  manufacturingEnterprise: '',
  coverImage: '',
  updator: localStorage.getItem("name")
})
const editRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  productionBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { max: 30, message: '最多输入30个字符', trigger: 'blur' }
  ],
  shelfLifeDays: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { type: 'number', message: '只能输入数字', trigger: 'blur' }
  ],
  productionLicenseNumber: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { max: 30, message: '最多输入30个字符', trigger: 'blur' }
  ],
  manufacturingEnterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { max: 30, message: '最多输入30个字符', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ]
}
const editFormRef = ref()
const handleEditAvatarSuccess = (val: any) => {
  editForm.value.coverImage = val
}
const beforeAvatarUpload = (rawFile: File) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png') {
    return true
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小不能超过 2MB!')
    return false
  } else {
    ElMessage.error('必须是jpg或png')
    return false
  }
}
const onEditDetail = () => {
  // 回显当前商品信息到editForm
  console.log(detail.value.goodsId);

  editForm.value = {
    id: detail.value.id,
    productName: detail.value.goodsId, // 注意这里用goodsId
    productionBatch: detail.value.productionBatch,
    shelfLifeDays: detail.value.shelfLifeDays,
    productionLicenseNumber: detail.value.productionLicenseNumber,
    manufacturingEnterprise: detail.value.manufacturingEnterprise,
    coverImage: detail.value.coverImage,
    updator: localStorage.getItem("name")
  }
  editDialogVisible.value = true
}
const onEditSubmitDetail = () => {
  (editFormRef.value as any).validate(async (valid: boolean) => {
    if (!valid) return
    try {
      const res = await axiostraceabliityw.post('/api/Traceability/UpdateProductTraceability', editForm.value)
      if (res.data && res.data.code === 200) {
        ElMessage.success(res.data.msg)
        editDialogVisible.value = false
          ; (editFormRef.value as any).resetFields()
        // 可选：刷新详情数据
        await finds()
      } else {
        ElMessage.error(res.data.msg || '修改失败')
      }
    } catch (error) {
      ElMessage.error('修改失败')
      console.error('修改失败:', error)
    }
  })
}

import { axiostraceabliityr } from '@/http/axiosRead'
const nums = ref()
// 打开弹窗并回显
const openProcessingDialogs = async (num: any) => {
  // 获取详情
  processingForm.value.id = processingDetail.value.id
  processingForm.value.productTraceabilityId = processingDetail.value.productTraceabilityId
  processingForm.value.teamsAndGroups = processingDetail.value.teamsAndGroups
  processingForm.value.personInCharge = processingDetail.value.personInCharge
  processingForm.value.yId = processingDetail.value.yId
  processingForm.value.rawMaterial = processingDetail.value.rawMaterial
  processingForm.value.fid = processingDetail.value.fid
  processingForm.value.auxiliaryMaterials = processingDetail.value.auxiliaryMaterials
  processingForm.value.tId = processingDetail.value.tId
  processingForm.value.additive = processingDetail.value.additive
  processingForm.value.bId = processingDetail.value.bId
  processingForm.value.baoCai = processingDetail.value.baoCai

  nums.value = num
  processingDialogVisibles.value = true
}

// #region 食品安全信息图片
const companyPhotoListDesc = ref<any[]>([])

//图片
const fetchCompanyPhotoDes = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoListDesc.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccessDes = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoListDesc.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUploads = (file: File) => {
  if (companyPhotoListDesc.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
// 删除图片
const removeQualificationPhotos = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoListDesc.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
// #endregion

// #region 相关材料第一模块
const companyPhotoListDescsy = ref<any[]>([])

//图片
const fetchCompanyPhotoDess = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoListDescsy.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccessDessy = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoListDescsy.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUploadssy = (file: File) => {
  if (companyPhotoListDescsy.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
// 删除图片
const removeQualificationPhotossy = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoListDescsy.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
// #endregion

// #region 相关材料第二模块
const companyPhotoListDescsyf = ref<any[]>([])

//图片
const fetchCompanyPhotoDessf = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyf.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccessDessyf = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoListDescsyf.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUploadssyf = (file: File) => {
  if (companyPhotoListDescsyf.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
// 删除图片
const removeQualificationPhotossyf = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyf.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
// #endregion

// #region 相关材料第三模块
const companyPhotoListDescsyt = ref<any[]>([])

//图片
const fetchCompanyPhotoDesst = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyt.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccessDessyt = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoListDescsyt.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUploadssyt = (file: File) => {
  if (companyPhotoListDescsyt.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
// 删除图片
const removeQualificationPhotossyt = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyt.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
// #endregion

// #region 相关材料第四模块
const companyPhotoListDescsyb = ref<any[]>([])

//图片
const fetchCompanyPhotoDessb = async (id: any) => {
  const res = await axiostraceabliityw.get('/api/CompanyPhoto/GetCompanyPhotos', { params: { traceId: id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyb.value = res.data.data
  }
}

// 上传成功
const handleQualificationPhotoSuccessDessyb = (res: any) => {
  if (res.code === 200 && res.data) {
    companyPhotoListDescsyb.value = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const beforeCompanyPhotoUploadssyb = (file: File) => {
  if (companyPhotoListDescsy.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}
// 删除图片
const removeQualificationPhotossyb = async (img: any) => {
  const res = await axiostraceabliityw.post('/api/CompanyPhoto/DeleteCompanyPhoto', null, { params: { id: img.id } })
  if (res.data.code === 200) {
    companyPhotoListDescsyb.value = res.data.data
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.data.msg || '删除失败')
  }
}
// #endregion

// #region 第三张功能
const processingForm = ref({
  id: 0,
  productTraceabilityId: route.query.id,
  teamsAndGroups: '',         // 班组
  personInCharge: '',         // 负责人
  yId: null,
  rawMaterial: '',            // 原料生产批次
  fid: null,
  auxiliaryMaterials: '',     // 辅料生产批次
  tId: null,
  additive: '',               // 添加剂生产批次
  bId: null,
  baoCai: ''                  // 包才生产批次
})
const processingDialogVisible = ref(false)
const processingDialogVisibles = ref(false)
const processingRules = {
  teamsAndGroups: [{ required: true, message: '请输入班组', trigger: 'blur' }],
  personInCharge: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  shengchanpici: [{ required: true, message: '请输入生产批次', trigger: 'blur' }]
}
const processingDetail = ref({
  id: 0,
  productTraceabilityId: route.query.id,
  teamsAndGroups: '',         // 班组
  personInCharge: '',         // 负责人
  yId: null,
  rawMaterial: '',            // 原料生产批次
  fid: null,
  auxiliaryMaterials: '',     // 辅料生产批次
  tId: null,
  additive: '',               // 添加剂生产批次
  bId: null,
  baoCai: ''                  // 包才生产批次
})
// 打开弹窗并回显
const openProcessingDialog = async () => {
  // 获取详情
  processingForm.value.id = processingDetail.value.id
  processingForm.value.productTraceabilityId = processingDetail.value.productTraceabilityId
  processingForm.value.teamsAndGroups = processingDetail.value.teamsAndGroups
  processingForm.value.personInCharge = processingDetail.value.personInCharge
  processingForm.value.yId = processingDetail.value.yId
  processingForm.value.rawMaterial = processingDetail.value.rawMaterial
  processingForm.value.fid = processingDetail.value.fid
  processingForm.value.auxiliaryMaterials = processingDetail.value.auxiliaryMaterials
  processingForm.value.tId = processingDetail.value.tId
  processingForm.value.additive = processingDetail.value.additive
  processingForm.value.bId = processingDetail.value.bId
  processingForm.value.baoCai = processingDetail.value.baoCai
  processingDialogVisible.value = true
}
const processingFormRef = ref()
// 保存
const handleProcessingSave = () => {
  processingFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    const apiUrl = '/api/DeepProcessingInformationDetail/AddOrUpdateDeepProcessingInformation'
    const res = await axiostraceabliityw.post(apiUrl, processingForm.value)
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      processingDialogVisible.value = false
      processingDialogVisibles.value = false
      // 刷新展示
      await fetchProcessingDetail()
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  })
}

// 获取展示详情
const fetchProcessingDetail = async () => {
  const res = await axiostraceabliityr.get('/api/DeepProcessingInformationDetail/GetDeepProcessingInformationDetail', {
    params: { ProductTraceabilityId: detail.value.id }
  })
  if (res.data && res.data.code === 200 && res.data.data) {
    processingDetail.value = res.data.data
    await fetchCompanyPhotoDes(processingDetail.value.id)
    await fetchCompanyPhotoDess(processingDetail.value.yId)
    await fetchCompanyPhotoDessf(processingDetail.value.fid)
    await fetchCompanyPhotoDesst(processingDetail.value.tId)
    await fetchCompanyPhotoDessb(processingDetail.value.bId)
  }
}


const DeepacuPhotoUploadUrl = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${processingDetail.value.id}`)
const DeepacuPhotoUploadUrly = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${processingDetail.value.yId}`)
const DeepacuPhotoUploadUrlf = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${processingDetail.value.fid}`)
const DeepacuPhotoUploadUrlt = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${processingDetail.value.tId}`)
const DeepacuPhotoUploadUrlb = computed(() => `http://10.222.11.20:5174/api/CompanyPhoto/UploadCompanyPhoto?traceId=${processingDetail.value.bId}`)
//#endregion

onMounted(async () => {
  bind()
  await finds();
  if (detail.value && detail.value.id) {
    await getBreedingDetail(detail.value.id);
  }
  await fetchAnimalCertImages()
  await getCompanyInfoDetail(detail.value.id)
  await fetchSlaughterDetail()
  await fetchProcessingDetail()
});

</script>

<style scoped>
.trace-detail-page {
  width: 100%;
  max-width: none;
  margin: 0;
  padding: 32px 0 48px 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  background: #f5f6fa;
}

.product-info-block,
.breeding-info-block2,
.health-info-block,
.animal-cert-block,
.company-info-block,
.company-photo-block {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 16px;
  padding: 32px 48px 32px 48px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.trace-detail-body {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.trace-detail-img {
  width: 180px;
  height: 180px;
  border-radius: 12px;
  overflow: hidden;
  margin-right: 40px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.trace-detail-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.trace-detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.trace-detail-title {
  font-size: 1.7rem;
  font-weight: bold;
  margin-bottom: 18px;
}

.trace-detail-row {
  display: flex;
  gap: 48px;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.trace-detail-section {
  margin-top: 18px;
}

.trace-detail-report {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.report-uploader {
  width: 90px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  cursor: pointer;
}

.report-img {
  width: 90px;
  height: 90px;
  object-fit: cover;
  border-radius: 8px;
}

.report-upload-btn {
  width: 90px;
  height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #aaa;
  font-size: 2rem;
}

.report-img-list {
  display: flex;
  gap: 12px;
  margin-left: 12px;
}

.report-img-item {
  position: relative;
  width: 90px;
  height: 90px;
}

.report-img-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  border-radius: 50%;
  color: #f56c6c;
  cursor: pointer;
  font-size: 18px;
  border: 1px solid #eee;
}

.breeding-info-card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.breeding-info-card-title {
  font-weight: bold;
  font-size: 1.15rem;
  color: #333;
}

.breeding-info-card-set-btn {
  margin-left: 16px;
}

.breeding-info-card-table {
  width: 100%;
}

.breeding-info-card-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.breeding-info-card-label {
  width: 100px;
  color: #888;
  text-align: right;
  margin-right: 8px;
  font-size: 1rem;
}

.breeding-info-card-value {
  width: 120px;
  color: #222;
  font-size: 1rem;
  margin-right: 32px;
  word-break: break-all;
}

.breeding-info-card-empty {
  color: #bbb;
  padding: 16px 0;
  text-align: center;
}

.block-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.block-title {
  font-weight: bold;
  font-size: 1.15rem;
  color: #333;
}

.block-set-btn {
  margin-left: 16px;
}

.animal-cert-uploader,
.animal-cert-upload-btn {
  width: 90px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  cursor: pointer;
}

.animal-cert-img-list {
  display: flex;
  gap: 12px;
  margin-left: 12px;
}

.animal-cert-img-item {
  position: relative;
  width: 90px;
  height: 90px;
}

.animal-cert-img {
  width: 90px;
  height: 90px;
  object-fit: cover;
  border-radius: 8px;
}

.animal-cert-img-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  color: #999;
}

.company-info-content-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 96px;
  margin-top: 8px;
}

.company-info-content-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 48px;
  margin-top: 8px;
}

.company-info-content-left {
  flex: 1;
  min-width: 300px;
  max-width: 50%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.company-info-content-right {
  min-width: 260px;
  max-width: 40%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-start;
}

.company-profile-text {
  white-space: pre-line;
  word-break: break-all;
  margin-left: 4px;
  margin-top: 4px;
}

.company-info-empty {
  color: #bbb;
  padding: 16px 0;
  text-align: center;
}

.trace-tabs {
  display: flex;
  gap: 32px;
  margin: 24px 0 16px 0;
}

.trace-tab-item {
  font-size: 16px;
  color: #333;
  padding: 6px 18px;
  border-radius: 6px 6px 0 0;
  background: #f7f7f7;
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
  transition: background 0.2s, color 0.2s;
}

.trace-tab-item.active {
  background: #fff;
  color: #409eff;
  font-weight: bold;
  border-bottom: 2px solid #409eff;
}

.company-photo-img-list {
  display: flex;
  gap: 12px;
  margin-left: 12px;
}

.company-photo-img-item {
  position: relative;
  width: 90px;
  height: 90px;
}

.company-photo-img {
  width: 90px;
  height: 90px;
  object-fit: cover;
  border-radius: 8px;
}

.company-photo-img-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  color: #999;
}

.company-photo-uploader,
.company-photo-upload-btn {
  width: 90px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  cursor: pointer;
}

.slaughter-block {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 16px;
  padding: 32px 48px 32px 48px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.slaughter-info-row {
  display: flex;
  gap: 96px;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.img-preview-dialog .el-dialog__body {
  padding: 0;
  background: transparent;
}
</style>